<template>
  <div class="profile-page">
    <div class="container py-4">
      <div class="row">
        <!-- 左侧菜单 -->
        <div class="col-lg-3">
          <div class="profile-sidebar card">
            <!-- 用户信息摘要 -->
            <div class="user-summary p-4 border-bottom">
              <div class="d-flex align-items-center">
                <div class="user-avatar me-3">
                  <el-avatar
                    :size="60"
                    :src="userStore.userInfo?.avatar || defaultAvatar"
                  />
                </div>
                <div class="user-info">
                  <h5 class="mb-1">{{ userStore.userInfo?.name || userStore.userInfo?.username }}</h5>
                  <p class="text-muted small mb-0">{{ getMemberLevelText(userStore.userInfo?.memberLevel) }}</p>
                </div>
              </div>
            </div>

            <!-- 导航菜单 -->
            <nav class="profile-nav">
              <el-menu
                :default-active="activeTab"
                class="profile-menu"
                @select="setActiveTab"
              >
                <el-menu-item index="overview">
                  <el-icon>
                    <DataBoard />
                  </el-icon>
                  <span>概览</span>
                </el-menu-item>
                <el-menu-item index="orders">
                  <el-icon>
                    <ShoppingBag />
                  </el-icon>
                  <span>我的订单</span>
                </el-menu-item>
                <el-menu-item index="profile">
                  <el-icon>
                    <User />
                  </el-icon>
                  <span>个人信息</span>
                </el-menu-item>
                <el-menu-item index="addresses">
                  <el-icon>
                    <Location />
                  </el-icon>
                  <span>收货地址</span>
                </el-menu-item>

              </el-menu>
            </nav>
          </div>
        </div>

        <!-- 右侧内容 -->
        <div class="col-lg-9">
          <!-- 概览页面 -->
          <div v-if="activeTab === 'overview'" class="overview-content">
            <!-- 统计卡片 -->
            <div class="stats-cards row mb-4">
              <div class="col-sm-6 col-lg-3 mb-3" v-for="stat in statsData" :key="stat.key">
                <el-card class="stat-card" :body-style="{ padding: '20px', textAlign: 'center' }">
                  <el-icon class="stat-icon" :class="stat.iconClass" size="32">
                    <component :is="stat.icon" />
                  </el-icon>
                  <h4 class="stat-number">{{ stat.value }}</h4>
                  <p class="stat-label text-muted">{{ stat.label }}</p>
                </el-card>
              </div>
            </div>

            <!-- 最近订单 -->
            <el-card class="mb-4">
              <template #header>
                <div class="d-flex justify-content-between align-items-center">
                  <span>最近订单</span>
                  <el-button type="primary" size="small" @click="setActiveTab('orders')">
                    查看全部
                  </el-button>
                </div>
              </template>
              <div class="recent-orders-list">
                <div class="order-item d-flex justify-content-between align-items-center p-3 border rounded mb-3"
                     v-for="order in recentOrders" :key="order.id">
                  <div class="order-info d-flex align-items-center">
                    <el-avatar :src="order.thumbnail" :size="60" shape="square" class="me-3" />
                    <div>
                      <h6 class="mb-1">{{ order.productName }}</h6>
                      <small class="text-muted">订单号：{{ order.orderNo }}</small>
                    </div>
                  </div>
                  <div class="order-status">
                    <el-tag :type="getOrderStatusType(order.status)">
                      {{ getOrderStatusText(order.status) }}
                    </el-tag>
                    <div class="order-amount fw-bold text-end mt-1">¥{{ order.amount }}</div>
                  </div>
                </div>
              </div>
            </el-card>
          </div>

          <!-- 订单管理 -->
          <div v-if="activeTab === 'orders'" class="orders-content">
            <el-card class="mb-4">
              <template #header>
                <div class="d-flex justify-content-between align-items-center">
                  <span>我的订单</span>
                  <div class="order-search">
                    <el-input
                      v-model="orderSearchKeyword"
                      placeholder="搜索订单..."
                      style="width: 200px;"
                      clearable
                    >
                      <template #append>
                        <el-button @click="searchOrders">
                          <el-icon>
                            <Search />
                          </el-icon>
                        </el-button>
                      </template>
                    </el-input>
                  </div>
                </div>
              </template>

              <!-- 订单状态筛选 -->
              <el-radio-group v-model="orderFilter" class="order-filters mb-3">
                <el-radio-button label="">全部</el-radio-button>
                <el-radio-button label="pending">待付款</el-radio-button>
                <el-radio-button label="processing">待发货</el-radio-button>
                <el-radio-button label="shipped">已发货</el-radio-button>
                <el-radio-button label="completed">已完成</el-radio-button>
              </el-radio-group>
            </el-card>

            <!-- 订单列表 -->
            <div class="orders-list">
              <el-card class="order-card mb-3" v-for="order in filteredOrders" :key="order.id">
                <template #header>
                  <div class="d-flex justify-content-between align-items-center">
                    <div class="order-meta">
                      <span class="order-date">{{ formatDate(order.createTime) }}</span>
                      <el-divider direction="vertical" />
                      <span class="order-no">订单号：{{ order.orderNo }}</span>
                    </div>
                    <el-tag :type="getOrderStatusType(order.status)">
                      {{ getOrderStatusText(order.status) }}
                    </el-tag>
                  </div>
                </template>
                <div class="order-items">
                  <div class="order-item d-flex align-items-center mb-3" v-for="item in order.items" :key="item.id">
                    <el-avatar :src="item.thumbnail" :size="80" shape="square" class="me-3" />
                    <div class="item-info flex-grow-1">
                      <h6 class="item-name mb-1">{{ item.name }}</h6>
                      <div class="item-specs text-muted small" v-if="item.specs">
                        <el-tag v-for="spec in item.specs" :key="spec" size="small" class="me-1">{{ spec }}</el-tag>
                      </div>
                    </div>
                    <div class="item-quantity text-muted me-3">
                      x{{ item.quantity }}
                    </div>
                    <div class="item-price fw-bold">
                      ¥{{ item.price }}
                    </div>
                  </div>
                </div>
                <div class="order-footer d-flex justify-content-between align-items-center">
                  <div class="order-total">
                    <span class="text-muted">共{{ order.items.length }}件商品 合计：</span>
                    <span class="total-amount fw-bold h5 text-danger ms-2">¥{{ order.totalAmount }}</span>
                  </div>
                  <div class="order-actions">
                    <el-button
                      v-if="order.status === 'pending'"
                      type="primary"
                      @click="payOrder(order)"
                    >
                      立即付款
                    </el-button>
                    <el-button
                      v-if="order.status === 'shipped'"
                      type="success"
                      @click="confirmReceived(order)"
                    >
                      确认收货
                    </el-button>
                    <el-button @click="viewOrderDetail(order)">
                      查看详情
                    </el-button>
                  </div>
                </div>
              </el-card>
            </div>
          </div>

          <!-- 个人信息编辑 -->
          <div v-if="activeTab === 'profile'" class="profile-edit-content">
            <el-card>
              <template #header>
                <span>个人信息</span>
              </template>
              <el-form :model="profileForm" label-width="100px" @submit.prevent="updateProfile">
                <div class="row">
                  <div class="col-md-8">
                    <el-form-item label="用户名">
                      <el-input v-model="profileForm.username" disabled>
                        <template #suffix>
                          <small class="text-muted">用户名不可修改</small>
                        </template>
                      </el-input>
                    </el-form-item>

                    <el-form-item label="昵称">
                      <el-input v-model="profileForm.name" placeholder="请输入昵称" />
                    </el-form-item>

                    <el-form-item label="手机号">
                      <el-input v-model="profileForm.phone" placeholder="请输入手机号">
                        <template #append>
                          <el-button @click="verifyPhone" :type="profileForm.phoneVerified ? 'success' : 'primary'">
                            {{ profileForm.phoneVerified ? '已验证' : '验证' }}
                          </el-button>
                        </template>
                      </el-input>
                    </el-form-item>

                    <el-form-item label="邮箱">
                      <el-input v-model="profileForm.email" placeholder="请输入邮箱">
                        <template #append>
                          <el-button @click="verifyEmail" :type="profileForm.emailVerified ? 'success' : 'primary'">
                            {{ profileForm.emailVerified ? '已验证' : '验证' }}
                          </el-button>
                        </template>
                      </el-input>
                    </el-form-item>

                    <el-form-item label="生日">
                      <el-date-picker
                        v-model="profileForm.birthday"
                        type="date"
                        placeholder="选择生日"
                        style="width: 100%;"
                      />
                    </el-form-item>

                    <el-form-item label="性别">
                      <el-radio-group v-model="profileForm.gender">
                        <el-radio label="male">男</el-radio>
                        <el-radio label="female">女</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </div>

                  <div class="col-md-4">
                    <div class="avatar-upload text-center">
                      <div class="avatar-preview mb-3">
                        <el-avatar
                          :src="profileForm.avatar || defaultAvatar"
                          :size="120"
                        />
                      </div>
                      <el-upload
                        class="avatar-uploader"
                        action="#"
                        :show-file-list="false"
                        :before-upload="beforeAvatarUpload"
                        :http-request="handleAvatarUpload"
                      >
                        <el-button type="primary">
                          <el-icon>
                            <Camera />
                          </el-icon>
                          更换头像
                        </el-button>
                      </el-upload>
                    </div>
                  </div>
                </div>

                <el-form-item>
                  <el-button type="primary" @click="updateProfile" :loading="updating">
                    {{ updating ? '保存中...' : '保存修改' }}
                  </el-button>
                  <el-button @click="resetProfile">重置</el-button>
                </el-form-item>
              </el-form>
            </el-card>
          </div>

          <!-- 收货地址管理 -->
          <div v-if="activeTab === 'addresses'" class="addresses-content">
            <div class="addresses-header d-flex justify-content-between align-items-center mb-4">
              <h5 class="mb-0">收货地址</h5>
              <el-button type="primary" @click="showAddressDialog()">
                <el-icon>
                  <Plus />
                </el-icon>
                添加地址
              </el-button>
            </div>

            <div class="addresses-list row">
              <div class="col-md-6 col-xl-4 mb-4" v-for="address in addresses"
                   :key="address.id || `temp-${Math.random()}`">
                <el-card class="address-card" :class="{ 
                  'border-primary': address.isDefault, 
                  'address-incomplete': !address.fullAddress || !address.fullAddress.trim() 
                }">
                  <div class="address-header d-flex justify-content-between align-items-start mb-3">
                    <div class="address-info">
                      <h6 class="mb-1">{{ address.name || '未设置姓名' }}</h6>
                      <p class="text-muted mb-0">{{ address.phone || '未设置手机号' }}</p>
                    </div>
                    <div class="address-tags">
                      <el-tag v-if="address.isDefault" type="primary" size="small">默认</el-tag>
                      <el-tag v-if="address.tag" type="info" size="small" class="ms-1">{{ address.tag }}</el-tag>
                    </div>
                  </div>
                  <div class="address-detail mb-3">
                    <p class="mb-0" v-if="address.fullAddress && address.fullAddress.trim()">
                      {{ address.fullAddress }}
                    </p>
                    <p v-else class="mb-0 text-muted">
                      <i class="fas fa-exclamation-circle me-1"></i>
                      地址信息不完整
                    </p>
                  </div>
                  <div class="address-actions">
                    <el-button size="small" type="primary" @click="editAddress(address)">
                      <i class="fas fa-edit me-1"></i>
                      {{ (!address.fullAddress || !address.fullAddress.trim()) ? '完善信息' : '编辑' }}
                    </el-button>
                    <el-button v-if="!address.isDefault" size="small" type="success"
                               @click="setDefaultAddressHandler(address)">
                      设为默认
                    </el-button>
                    <el-button size="small" type="danger" @click="deleteAddressHandler(address)">
                      删除
                    </el-button>
                  </div>
                </el-card>
              </div>
            </div>

            <!-- 空地址列表提示 -->
            <div v-if="addresses.length === 0" class="text-center text-muted py-5">
              <i class="fas fa-map-marker-alt fa-3x mb-3 text-muted"></i>
              <h6>还没有收货地址</h6>
              <p>点击上方"添加地址"按钮添加第一个地址</p>
            </div>
          </div>


        </div>
      </div>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      :title="addressForm.id ? '编辑地址' : '添加地址'"
      width="500px"
    >
      <el-form :model="addressForm" label-width="100px" ref="addressFormRef">
        <el-form-item label="收货人姓名" required>
          <el-input v-model="addressForm.name" />
        </el-form-item>

        <el-form-item label="手机号" required>
          <el-input v-model="addressForm.phone" />
        </el-form-item>

        <el-form-item label="所在地区" required>
          <el-cascader
            v-model="regionCodes"
            :options="regionOptions"
            :props="cascaderProps"
            placeholder="请选择省市区"
            style="width: 100%;"
            @change="onRegionChange"
          />
        </el-form-item>

        <el-form-item label="详细地址" required>
          <el-input
            v-model="addressForm.detail"
            type="textarea"
            :rows="3"
            placeholder="请输入详细地址"
          />
        </el-form-item>
        
        <el-form-item label="地址标签">
          <el-select v-model="addressForm.tag" placeholder="选择地址标签" clearable>
            <el-option label="家" value="家" />
            <el-option label="公司" value="公司" />
            <el-option label="学校" value="学校" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="addressForm.isDefault">设为默认地址</el-checkbox>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAddress" :loading="savingAddress">
            {{ savingAddress ? '保存中...' : '保存' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import { Camera, Clock, DataBoard, Location, Plus, Search, ShoppingBag, Star, User } from '@element-plus/icons-vue'

// API导入
import { getLoginUser, updateUser } from '@/api/user'
import { 
  getUserAddresses, 
  addAddress, 
  updateAddress, 
  deleteAddress as deleteAddressAPI, 
  setDefaultAddress as setDefaultAddressAPI, 
  type AddressVO 
} from '@/api/address'


// 使用region-tree-data库获取完整的省市数据
import { regionData, CodeToText } from 'region-tree-data'

// 定义类型
interface OrderItem {
  id: number
  name: string
  thumbnail: string
  specs?: string[]
  quantity: number
  price: number
}

interface Order {
  id: number
  orderNo: string
  status: OrderStatus
  totalAmount: number
  amount: number // 添加amount属性用于显示
  createTime: Date
  items: OrderItem[]
  // 为最近订单添加的属性
  thumbnail?: string
  productName?: string
}

interface Product {
  id: number
  name: string
  price: number
  thumbnail: string
}

interface Address {
  id: number | null
  receiverName: string
  phone: string
  regionCodes: string[]
  detailAddress: string
  fullAddress: string
  isDefault: boolean
}

type OrderStatus = 'pending' | 'processing' | 'shipped' | 'completed' | 'cancelled'

const router = useRouter()
const userStore = useUserStore()

// 占位符图片生成函数
const placeholderImage = (width: number, height: number) => {
  return `https://picsum.photos/${width}/${height}?random=${Math.floor(Math.random() * 1000)}`
}

// 默认头像
const defaultAvatar = placeholderImage(120, 120)

// 页面状态
const loading = ref(false)
const updating = ref(false)
const savingAddress = ref(false)
const activeTab = ref('overview')
const addressDialogVisible = ref(false)

// 用户信息 
const userInfo = reactive({
  id: null,
  username: '',
  name: '',
  avatar: '',
  memberLevel: 1,
  phone: '',
  email: '',
  birthday: '',
  gender: ''
})

// 个人信息表单
const profileForm = reactive({
  username: '',
  name: '',
  phone: '',
  email: '',
  birthday: '',
  gender: '',
  avatar: '',
  phoneVerified: true,
  emailVerified: false
})

// 统计数据
const statsData = computed(() => [
  {
    key: 'orders',
    icon: ShoppingBag,
    iconClass: 'text-primary',
    value: userStats.value.totalOrders,
    label: '总订单'
  },
  {
    key: 'pending',
    icon: Clock,
    iconClass: 'text-warning',
    value: userStats.value.pendingOrders,
    label: '待付款'
  }

])

// 用户统计（将从API获取）
const userStats = ref({
  totalOrders: 0,
  pendingOrders: 0
})

// 最近订单
const recentOrders = ref<Order[]>([])

// 推荐商品
const recommendedProducts = ref<Product[]>([])

// 订单相关
const orderSearchKeyword = ref('')
const orderFilter = ref('')
const orders = ref<Order[]>([])

// 地址相关
const addresses = ref<AddressVO[]>([])
const addressForm = reactive({
  id: '',
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  street: '',
  detail: '',
  postcode: '',
  isDefault: false,
  tag: ''
})
const regionCodes = ref<string[]>([])

// 地区数据配置
const regionOptions = regionData

// 使用库自带的CodeToText函数进行代码转文本
const codeToText = (codes: string[]): string => {
  return codes.map(code => CodeToText[code] || '').join(' ')
}

// 级联选择器配置
const cascaderProps = {
  value: 'value',
  label: 'label',
  children: 'children'
}

// 计算属性
const filteredOrders = computed(() => {
  let filtered = orders.value

  if (orderFilter.value) {
    filtered = filtered.filter(order => order.status === orderFilter.value)
  }

  if (orderSearchKeyword.value) {
    filtered = filtered.filter(order =>
      order.orderNo.includes(orderSearchKeyword.value) ||
      order.items.some(item => item.name.includes(orderSearchKeyword.value))
    )
  }

  return filtered
})

// 方法
const setActiveTab = (tab: string) => {
  activeTab.value = tab
}

// 会员等级文本函数
const getMemberLevelText = (level?: number) => {
  if (!level) return '普通用户'
  const levelTexts: Record<number, string> = {
    1: '普通用户',
    2: '铜牌会员',
    3: '银牌会员',
    4: 'VIP会员',
    5: '钻石会员'
  }
  return levelTexts[level] || '普通用户'
}

const getOrderStatusType = (status: string): 'success' | 'warning' | 'info' | 'danger' | '' => {
  const statusTypes: Record<OrderStatus, 'success' | 'warning' | 'info' | 'danger' | ''> = {
    'pending': 'warning',
    'processing': 'info',
    'shipped': 'info',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusTypes[status as OrderStatus] || ''
}

const getOrderStatusText = (status: string) => {
  const statusTexts: Record<OrderStatus, string> = {
    'pending': '待付款',
    'processing': '处理中',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusTexts[status as OrderStatus] || '未知'
}

const formatDate = (date: Date) => {
  return date.toLocaleDateString('zh-CN')
}

// 移除模拟数据，使用真实API







// 业务方法
const fetchUserData = async () => {
  loading.value = true
  try {
    // 获取当前登录用户信息
    const userResponse = await getLoginUser()
    Object.assign(userInfo, userResponse.data)
    Object.assign(profileForm, userResponse.data)

    // 获取用户地址列表
    await loadAddresses()

    // 获取收藏数量
    await loadUserStats()

    // 订单数据将在loadUserStats中获取

  } catch (error) {
    console.error('获取用户数据失败:', error)
    ElMessage.error('获取用户数据失败')
  } finally {
    loading.value = false
  }
}

const updateProfile = async () => {
  updating.value = true
  try {
    // 调用真实的更新API
    if (userInfo.id) {
      // 转换生日格式为 LocalDateTime 格式
      let birthdayStr = ''
      if (profileForm.birthday) {
        const birthday: any = profileForm.birthday
        if (birthday instanceof Date) {
          birthdayStr = birthday.toISOString().split('T')[0] + 'T00:00:00'
        } else if (typeof birthday === 'string') {
          birthdayStr = birthday.includes('T') 
            ? birthday 
            : birthday + 'T00:00:00'
        }
      }
      
      await updateUser({
        id: userInfo.id,
        name: profileForm.name,
        phone: profileForm.phone,
        email: profileForm.email,
        birthday: birthdayStr,
        avatar: profileForm.avatar
      })
    }
    
    Object.assign(userInfo, profileForm)
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error('更新失败:', error)
    ElMessage.error('更新失败')
  } finally {
    updating.value = false
  }
}

const resetProfile = () => {
  Object.assign(profileForm, userInfo)
}

const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
  }
  return isJPG && isLt2M
}

const handleAvatarUpload = async (options: any) => {
  const file = options.file
  const reader = new FileReader()
  reader.onload = (e) => {
    profileForm.avatar = e.target?.result as string
  }
  reader.readAsDataURL(file)
}

const verifyPhone = () => {
  ElMessage.info('验证码已发送至您的手机')
}

const verifyEmail = () => {
  ElMessage.info('验证邮件已发送至您的邮箱')
}

const searchOrders = () => {
  console.log('搜索订单:', orderSearchKeyword.value)
}

const payOrder = (order: Order) => {
  ElMessage.success('跳转到支付页面')
}

const confirmReceived = (order: Order) => {
  order.status = 'completed'
  ElMessage.success('确认收货成功')
}

const viewOrderDetail = (order: Order) => {
  router.push(`/orders/${order.id}`)
}
const showAddressDialog = (address?: AddressVO) => {
  if (address) {
    addressForm.id = address.id
    addressForm.name = address.name
    addressForm.phone = address.phone
    addressForm.province = address.province
    addressForm.city = address.city
    addressForm.district = address.district
    addressForm.street = address.street || ''
    addressForm.detail = address.detail
    addressForm.postcode = address.postcode || ''
    addressForm.isDefault = address.isDefault
    addressForm.tag = address.tag || ''
    
    // 设置级联选择器的值（这里需要根据省市区名称找到对应的code）
    regionCodes.value = []
  } else {
    resetAddressForm()
  }
  addressDialogVisible.value = true
}

const resetAddressForm = () => {
  Object.assign(addressForm, {
    id: '',
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    street: '',
    detail: '',
    postcode: '',
    isDefault: false,
    tag: ''
  })
  regionCodes.value = []
}

const editAddress = (address: AddressVO) => {
  showAddressDialog(address)
}

const setDefaultAddressHandler = async (address: AddressVO) => {
  try {
    await setDefaultAddressAPI(address.id)
    ElMessage.success('已设置为默认地址')
    await loadAddresses()
  } catch (error) {
    ElMessage.error('设置默认地址失败')
  }
}

const deleteAddressHandler = async (address: AddressVO) => {
  try {
    await deleteAddressAPI(address.id)
    ElMessage.success('地址删除成功')
    await loadAddresses()
  } catch (error) {
    ElMessage.error('删除地址失败')
  }
}

// 加载地址列表
const loadAddresses = async () => {
  try {
    console.log('开始加载地址列表...')
    const response = await getUserAddresses()
    console.log('地址API响应:', response)
    console.log('地址数据:', response.data)
    addresses.value = response.data
    console.log('设置后的地址列表:', addresses.value)
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 加载用户统计数据
const loadUserStats = async () => {
  try {
    // 获取用户订单数据来计算统计
    if (userInfo.id) {
      await loadUserOrders()
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 加载用户订单数据
const loadUserOrders = async () => {
  try {
    // 使用现有的getUserOrders API
    const { getUserOrders } = await import('@/api/order')
    
         // 获取所有订单用于统计
     const allOrdersResponse = await getUserOrders(
       userInfo.username || '', 
       '', // 不限制状态
       1, 
       100 // 获取更多数据用于统计
     )
     
     // 转换API返回的Order类型为Profile页面使用的Order类型
     const apiOrders = allOrdersResponse.data.records || []
     console.log('API返回的订单数据:', apiOrders)
     
     orders.value = apiOrders.map(apiOrder => {
       // 检查多个可能的时间字段，优先使用checkoutTime (下单时间)
       let orderTime = apiOrder.checkoutTime || apiOrder.createdTime
       
       // 验证时间字段是否有效
       let parsedTime = orderTime ? new Date(orderTime) : null
       
       // 如果时间字段为空、无效或者是1970年，使用当前时间作为后备
       if (!orderTime || !parsedTime || isNaN(parsedTime.getTime()) || parsedTime.getFullYear() < 2020) {
         console.warn('订单时间字段无效，使用当前时间:', {
           orderId: apiOrder.id,
           orderNo: apiOrder.orderNo,
           checkoutTime: apiOrder.checkoutTime,
           createdTime: apiOrder.createdTime,
           parsedTime: parsedTime
         })
         orderTime = new Date().toISOString()
         parsedTime = new Date()
       }
       
       console.log('订单时间处理:', {
         orderId: apiOrder.id,
         originalTime: orderTime,
         parsedTime: parsedTime
       })
       
       return {
         id: apiOrder.id,
         orderNo: apiOrder.orderNo,
         status: apiOrder.status as any,
         totalAmount: apiOrder.totalPay,
         amount: apiOrder.totalPay,
         createTime: parsedTime,
         items: [], // 暂时为空，如需要可以从orderItems获取
         productName: `订单 ${apiOrder.orderNo}`,
         thumbnail: '/api/placeholder/60/60'
       }
     })
    
    // 计算统计数据
    const totalOrders = orders.value.length
    const pendingOrders = orders.value.filter(order => order.status === 'pending').length
    
    userStats.value = {
      totalOrders,
      pendingOrders
    }
    
         // 设置最近订单（最新的3个）
     recentOrders.value = orders.value
       .sort((a, b) => b.createTime.getTime() - a.createTime.getTime())
       .slice(0, 3)
    
    console.log('用户订单统计:', userStats.value)
    console.log('最近订单:', recentOrders.value)
    
  } catch (error) {
    console.error('获取用户订单失败:', error)
    // 设置默认值避免显示错误
    userStats.value = {
      totalOrders: 0,
      pendingOrders: 0
    }
    recentOrders.value = []
  }
}

const onRegionChange = (codes: string[]) => {
  regionCodes.value = codes
  if (codes && codes.length === 3) {
    const regionNames = codeToText(codes).split(' ')
    addressForm.province = regionNames[0] || ''
    addressForm.city = regionNames[1] || ''
    addressForm.district = regionNames[2] || ''
  }
}

const saveAddress = async () => {
  savingAddress.value = true
  try {
    // 将级联选择的结果转换为省市区字段
    if (regionCodes.value.length === 3) {
      const regionNames = codeToText(regionCodes.value).split(' ')
      addressForm.province = regionNames[0] || ''
      addressForm.city = regionNames[1] || ''
      addressForm.district = regionNames[2] || ''
    }

    if (addressForm.id) {
      // 更新地址
      await updateAddress({
        id: addressForm.id,
        name: addressForm.name,
        phone: addressForm.phone,
        province: addressForm.province,
        city: addressForm.city,
        district: addressForm.district,
        street: addressForm.street,
        detail: addressForm.detail,
        postcode: addressForm.postcode,
        isDefault: addressForm.isDefault,
        tag: addressForm.tag
      })
    } else {
      // 添加新地址
      await addAddress({
        name: addressForm.name,
        phone: addressForm.phone,
        province: addressForm.province,
        city: addressForm.city,
        district: addressForm.district,
        street: addressForm.street,
        detail: addressForm.detail,
        postcode: addressForm.postcode,
        isDefault: addressForm.isDefault,
        tag: addressForm.tag
      })
    }

    ElMessage.success('地址保存成功')
    addressDialogVisible.value = false
    
    // 重新加载地址列表
    await loadAddresses()

  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    savingAddress.value = false
  }
}

onMounted(() => {
  if (!userStore.isLoggedIn) {
    router.push('/login')
    return
  }

  fetchUserData()
})
</script>

<style scoped>
/* 用户摘要 */
.user-avatar img {
  width: 60px;
  height: 60px;
  object-fit: cover;
}

/* 导航菜单 */
.profile-nav .nav-link {
  color: #666;
  border: none;
  border-radius: 8px;
  margin-bottom: 5px;
  transition: all 0.3s ease;
}

.profile-nav .nav-link:hover,
.profile-nav .nav-link.active {
  background-color: #007bff;
  color: white;
}

/* 统计卡片 */
.stat-card {
  border: none;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.15);
}

.stat-number {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 0;
}

/* 订单项目 */
.order-item .order-thumbnail,
.order-item .item-thumbnail {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 6px;
}

.order-card {
  border: none;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.order-card:hover {
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.12);
}

.order-card .card-header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

/* 订单筛选 */
.order-filters .btn-check:checked + .btn {
  background-color: #007bff;
  color: white;
}

/* 推荐商品 */
.product-card img {
  width: 100%;
  height: 100px;
  object-fit: cover;
}

.product-name {
  font-size: 14px;
  line-height: 1.3;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 地址卡片 */
.address-card {
  border: 2px solid #e9ecef;
  transition: all 0.3s ease;
}

.address-card:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.address-card.border-primary {
  border-color: #007bff !important;
}

.address-card.address-incomplete {
  border-color: #ffc107;
  background-color: #fffbf0;
}

.address-card.address-incomplete:hover {
  box-shadow: 0 5px 15px rgba(255, 193, 7, 0.2);
}

.incomplete-address {
  padding: 8px 12px;
  border-left: 3px solid #ffc107;
  background-color: #fffef5;
  border-radius: 4px;
}

.address-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.address-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
  justify-content: flex-start;
}

.address-actions .el-button {
  flex: 0 0 auto;
  white-space: nowrap;
}

/* 个人信息编辑 */
.avatar-upload .avatar-preview img {
  border: 3px solid #e9ecef;
}
</style> 